package co.gov.medellin.ssti.sub.web.action;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.springframework.beans.factory.annotation.Autowired;

import co.gov.medellin.ssti.sub.model.dao.exception.DAOException;
import co.gov.medellin.ssti.sub.model.service.GrupoFamiliarService;
import co.gov.medellin.ssti.sub.model.vo.BeneficiarioVO;
import co.gov.medellin.ssti.sub.paoyer.administration.exception.AdministrationUserException;
import co.gov.medellin.ssti.sub.paoyer.administration.model.vo.UserVO;
import co.gov.medellin.ssti.sub.paoyer.administration.util.AccessControl;
import co.gov.medellin.ssti.sub.paoyer.common.exception.CommonUserException;
import co.gov.medellin.ssti.sub.paoyer.common.exception.UserException;

public class GuardarGrupoFamiliarAction extends Action {
	@Autowired
	GrupoFamiliarService grupoFamiliarServiceImpl;

	/**
	 * This is the main action called from the Struts framework.
	 * 
	 * @param mapping
	 *            The ActionMapping used to select this instance.
	 * @param form
	 *            The optional ActionForm bean for this request.
	 * @param request
	 *            The HTTP Request we are processing.
	 * @param response
	 *            The HTTP Response we are processing.
	 * @return
	 * @throws java.io.IOException
	 * @throws javax.servlet.ServletException
	 */
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		ActionMessages messages = new ActionMessages();
		try {
			AccessControl access = new AccessControl();
			access.validateAccess(mapping, request, response);

			HttpSession session = request.getSession();
			String strOrigen = request.getParameter("origen");
			// Para la auditoria de registros
			UserVO user = (UserVO) session.getAttribute("userInfo");
			String terminalAddress = "WEB=" + request.getRemoteAddr();
			Calendar c = Calendar.getInstance();
			SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

			if (strOrigen.equals("nuevo")) {
				Long codeCabeza = new Long(request.getParameter("code"));
				String strnombre = request.getParameter("nombre");
				Long codeParentesco = new Long(
						request.getParameter("codeParentesco"));

				try {

					String inserto[] = grupoFamiliarServiceImpl.insert(
							codeCabeza, strnombre, codeParentesco,
							user.getName(), terminalAddress,
							dateFormat.format(c.getTime()));
					@SuppressWarnings("unchecked")
					List<BeneficiarioVO> lbene = (List<BeneficiarioVO>) session
							.getAttribute("bene");
					BeneficiarioVO objBeneVO = (BeneficiarioVO) lbene.get(0);
					session.removeAttribute("bene");
					objBeneVO.setGrupoFamiliar(request.getParameter("nombre"));
					Collection<BeneficiarioVO> bene = new LinkedList<BeneficiarioVO>();
					bene.add(objBeneVO);
					session.setAttribute("bene", bene);

					if (inserto[0].equals("false")) {
						return mapping.findForward("fail");
					} else {
						session.setAttribute("gf_code", inserto[1]);
						session.setAttribute("msGFOK",
								"El grupo familiar se creo exitosamente. Ahora puede asignar al beneficario.");
					}
				} catch (DAOException e) {
					System.err.println("/******** TDSUB - cwsub");
					e.printStackTrace();
					System.err.println("TDSUB - cwsub ********/");
					return mapping.findForward("fail");
				}
			} else {
				Long codeParentesco = new Long(
						request.getParameter("codeParentesco"));
				Long codeBene = new Long(
						request.getParameter("codeBeneficiario"));
				Long codeGF = new Long(request.getParameter("codeGF"));
				session.setAttribute("gf_code", codeGF.toString());
				@SuppressWarnings("unchecked")
				List<BeneficiarioVO> lbene = (List<BeneficiarioVO>) session
						.getAttribute("bene");
				BeneficiarioVO objBeneVO = (BeneficiarioVO) lbene.get(0);
				session.removeAttribute("bene");
				objBeneVO.setGrupoFamiliar(request.getParameter("nombreGF"));
				Collection<BeneficiarioVO> bene = new LinkedList<BeneficiarioVO>();
				bene.add(objBeneVO);
				session.setAttribute("bene", bene);
				try {

					if (grupoFamiliarServiceImpl
							.asignarBeneficiarioAGrupoFamiliar(codeBene,
									codeGF, codeParentesco, user.getCode()
											.toString(), terminalAddress,
									dateFormat.format(c.getTime()))) {

						String strMessage = (String) session
								.getAttribute("Option");
						if (strMessage != null && !strMessage.equals("")) {
							session.setAttribute(
									"msgNGF",
									"El grupo familiar fue creado exitosamente, ahora puede asignar los beneficiarios.");
						}
						return mapping.findForward("success");
					} else {
						return mapping.findForward("fail1");
					}

				} catch (DAOException e) {
					System.err.println("/******** TDSUB - cwsub");
					e.printStackTrace();
					System.err.println("TDSUB - cwsub ********/");
					return mapping.findForward("fail1");
				}
			}
		} catch (UserException ue) {
			messages.add("msgWarn", new ActionMessage("loginForm.message."
					+ ue.getExceptionVO().getId()));
			saveMessages(request, messages);
			if (ue.getExceptionVO().getId() == AdministrationUserException.ENDED_SESSION) {
				response.sendRedirect(request.getContextPath() + "/index.jsp");
			} else if (ue.getExceptionVO().getId() == CommonUserException.NOT_ALLOWED_RESOURCE) {
				response.sendRedirect(request.getContextPath()
						+ "/admin/tile/invalidatedResource.jsp");
			} else {
				return mapping.getInputForward();
			}

		}

		return mapping.findForward("success");
	}
}